package com.jinly.ryder.ssh.web;

import com.jinly.ryder.manage.service.HostInstanceService;
import com.jinly.ryder.manage.service.model.HostInstance;
import com.jinly.ryder.ssh.command.model.OsInfo;
import com.jinly.ryder.ssh.service.SshConnectService;
import com.jinly.ryder.ssh.service.model.SshConnect;
import com.jinly.ryder.ssh.web.vo.SshConnectVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/sshConnect")
@RequiredArgsConstructor
public class SshConnectController {

    private final SshConnectService sshConnectService;

    private final HostInstanceService hostInstanceService;

    @PutMapping("test")
    public void testConnect(@RequestBody SshConnectVO sshConnectVO) {
        HostInstance hostInstance = hostInstanceService.getInstance(sshConnectVO.getHostId());
        if (hostInstance != null) {
            SshConnect sshConnect = new SshConnect();
            BeanUtils.copyProperties(sshConnectVO, sshConnect);
            sshConnect.setHost(hostInstance.getHost());
            OsInfo osInfo = sshConnectService.testConnect(sshConnect);
            if (sshConnect.getType() != 1) {
                try {
                    sshConnect.setType(1);
                    sshConnectService.testConnect(sshConnect);
                    log.info("host{}已经免登", sshConnect.getHost());
                } catch (Exception e) {
                    log.info("host{}开始设置免登", sshConnect.getHost());
                    sshConnect.setType(sshConnectVO.getType());
                    sshConnectService.sshCopyId(sshConnect);
                    log.info("host{}设置免登成功", sshConnect.getHost());
                    if (osInfo != null) {
                        BeanUtils.copyProperties(osInfo, hostInstance);
                        hostInstanceService.saveHost(hostInstance);
                    }
                }
            }
        }
    }
}
